package quangtqServlet;

import helper.ConnectionHelper;
import javax.servlet.annotation.WebServlet;

import java.io.IOException;
import java.sql.*;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="SendMailServlet", urlPatterns={"/SendMailServlet"})
public class SendMailServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    {
        String toUser = req.getParameter("to");
        String cc = req.getParameter("cc");
        String bcc = req.getParameter("bcc");
        String subject = req.getParameter("subject");
        String mailContent = req.getParameter("rte1");
        Boolean hasFile = req.getParameter("hasFile").equals("1") ? true : false;

        String fromUser = (String)req.getSession().getAttribute("username") + "@srs.com";
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String sentDate = dateFormat.format(date);

        Connection con = ConnectionHelper.GetConnection();

        //Insert users in To field
        insertTo(con, toUser, subject, fromUser, cc, sentDate, mailContent, hasFile);

        //Insert users in Cc field
        insertCc(con, toUser, subject, fromUser, cc, sentDate, mailContent, hasFile);

        //Insert users in Bcc field
        insertBcc(con, toUser, subject, fromUser, cc, bcc, sentDate, mailContent, hasFile);

        //Insert current user
        String currentUser = (String)req.getSession().getAttribute("username");
        insertCurrentUser(con, toUser, subject, fromUser, cc, bcc, sentDate, mailContent,
                currentUser, hasFile);

        //Set Session MailID
        if(hasFile)
        {
            setSessionMailID(con, currentUser, sentDate, req);
        }

        //Return javascript
        res.setContentType("text/xml");
        res.setHeader("Cache-Control", "no-cache");
        res.getWriter().write("ok");
    }

    private void insertTo(Connection con, String toUser, String subject, String fromUser,
            String cc, String sentDate, String mailContent, boolean hasFile)
    {
        StringTokenizer toUserToken = new StringTokenizer(toUser, ", ");

        try
        {
            while(toUserToken.hasMoreElements())
            {
                String user = toUserToken.nextToken();
                String userName = user.substring(0, user.indexOf("@"));
                String sql = "INSERT INTO Mails(UserName, Subject, FromUser, ToUser, Cc, " +
                        "SentDate, MailContent, HasFile, Inbox, IsNew) " +
                        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                PreparedStatement p = con.prepareStatement(sql);
                p.setString(1, userName);
                p.setString(2, subject);
                p.setString(3, fromUser);
                p.setString(4, toUser);
                p.setString(5, cc);
                p.setString(6, sentDate);
                p.setString(7, mailContent);
                p.setBoolean(8, hasFile);
                p.setBoolean(9, true);
                p.setBoolean(10, true);

                p.executeUpdate();
            }
        }
        catch (SQLException ex)
        {
            System.out.print(ex.getMessage());
        }
    }

    private void insertCc(Connection con, String toUser, String subject, String fromUser,
            String cc, String sentDate, String mailContent, boolean hasFile)
    {
        StringTokenizer ccToken = null;

        try
        {
            if(!cc.equals(""))
            {
                ccToken = new StringTokenizer(cc, ", ");

                while(ccToken.hasMoreElements())
                {
                    String user = ccToken.nextToken();
                    String userName = user.substring(0, user.indexOf("@"));

                    String sql = "INSERT INTO Mails(UserName, Subject, FromUser, ToUser, Cc, "
                        + "SentDate, MailContent, HasFile, Inbox, IsNew) "
                        + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement p = con.prepareStatement(sql);

                    p.setString(1, userName);
                    p.setString(2, subject);
                    p.setString(3, fromUser);
                    p.setString(4, toUser);
                    p.setString(5, cc);
                    p.setString(6, sentDate);
                    p.setString(7, mailContent);
                    p.setBoolean(8, hasFile);
                    p.setBoolean(9, true);
                    p.setBoolean(10, true);

                    p.executeUpdate();
                }
            }
        }
        catch (SQLException ex)
        {
            System.out.print(ex.getMessage());
        }
    }

    private void insertBcc(Connection con, String toUser, String subject, String fromUser,
            String cc, String bcc, String sentDate, String mailContent, boolean hasFile)
    {
        StringTokenizer bccToken = null;

        try
        {
            if(!bcc.equals(""))
            {
                bccToken = new StringTokenizer(bcc, ", ");

                while(bccToken.hasMoreElements())
                {
                    String user = bccToken.nextToken();
                    String userName = user.substring(0, user.indexOf("@"));

                    String sql = "INSERT INTO Mails(UserName, Subject, FromUser, ToUser, Cc, Bcc, "
                        + "SentDate, MailContent, HasFile, Inbox, IsNew) "
                        + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement p = con.prepareStatement(sql);

                    p.setString(1, userName);
                    p.setString(2, subject);
                    p.setString(3, fromUser);
                    p.setString(4, toUser);
                    p.setString(5, cc);
                    p.setString(6, bcc);
                    p.setString(7, sentDate);
                    p.setString(8, mailContent);
                    p.setBoolean(9, hasFile);
                    p.setBoolean(10, true);
                    p.setBoolean(11, true);

                    p.executeUpdate();
                }
            }
        }
        catch (SQLException ex)
        {
            System.out.print(ex.getMessage());
        }
    }

    private void insertCurrentUser(Connection con, String toUser, String subject, String fromUser,
            String cc, String bcc, String sentDate, String mailContent, String currentUser, boolean hasFile)
    {
        try
        {
            String sql = "INSERT INTO Mails(UserName, Subject, FromUser, ToUser, Cc, Bcc, "
                + "SentDate, MailContent, HasFile, Inbox, IsNew) "
                + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            PreparedStatement p = con.prepareStatement(sql);

            p.setString(1, currentUser);
            p.setString(2, subject);
            p.setString(3, fromUser);
            p.setString(4, toUser);
            p.setString(5, cc);
            p.setString(6, bcc);
            p.setString(7, sentDate);
            p.setString(8, mailContent);
            p.setBoolean(9, hasFile);
            p.setBoolean(10, false);
            p.setBoolean(11, false);

            p.executeUpdate();
        }
        catch (SQLException ex)
        {
            System.out.print(ex.getMessage());
        }
    }

    private void setSessionMailID(Connection con, String currentUser, String sentDate,
            HttpServletRequest req)
    {
        try
        {
            String sql = "SELECT MailID FROM Mails WHERE UserName = ? AND SentDate = ?";
            PreparedStatement p = con.prepareStatement(sql);

            p.setString(1, currentUser);
            p.setString(2, sentDate);

            ResultSet rs = p.executeQuery();
            if(rs.next())
            {
                req.getSession().setAttribute("MailID", rs.getString(1));
            }
        }
        catch (SQLException ex)
        {
            System.out.print(ex.getMessage());
        }
    }
}
